import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import skimage
import time
import copy
import cv2
import os


def paint_region_with_avg_intensity(img, rp, mi, channel):
    for i in range(rp.shape[0]):
        img[rp[i][0]][rp[i][1]][channel] = mi
    return img


cv2_img = lambda bgr: cv2.merge(list(cv2.split(bgr))[::-1])


def image_equalizeHist(img,color='HSV'):
    if color =='HSV':
        img_HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        H, S, V = cv2.split(img_HSV)
        eq_V = cv2.equalizeHist(V)
        img_HSV = cv2.merge([H, S, eq_V])
        img_hist = cv2.cvtColor(img_HSV, cv2.COLOR_HSV2BGR)
    elif color == 'YCrCb':
        img_YCrCb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
        Y, Cr, Cb = cv2.split(img_YCrCb)
        eq_Y = cv2.equalizeHist(Y)
        img_YCrCb = cv2.merge([eq_Y, Cr, Cb])
        img_hist = cv2.cvtColor(img_YCrCb, cv2.COLOR_YCrCb2BGR)
    # elif color == 'YUV':
    #     img_YUV = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
    #     L, a, b = cv2.split(img_YUV)
    #     eq_L = cv2.equalizeHist(L)
    #     img_YUV = cv2.merge([eq_L, a, b])
    #     img_hist = cv2.cvtColor(img_YUV, cv2.COLOR_YUV2BGR)
    elif color == 'LAB':
        img_LAB = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
        L, A, B = cv2.split(img_LAB)
        eq_L = cv2.equalizeHist(L)
        img_LAB = cv2.merge([eq_L, A, B])
        img_hist = cv2.cvtColor(img_LAB, cv2.COLOR_Lab2BGR)
    elif color == 'gray':
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img_hist = cv2.equalizeHist(img_gray)
    return img_hist


def image_blur(img,blur="GaussianBlur"):
    if blur=="GaussianBlur":
        img_blur = cv2.GaussianBlur(img,(5,5),0)
    elif blur=="medianBlur":
        img_blur = cv2.medianBlur(img, 5)
    elif blur=="blur":
        img_blur = cv2.blur(img, (3,3))
    elif blur=="bilateralFilter":
        img_blur = cv2.bilateralFilter(img,9,75,75)
    return img_blur


def image_slic(args):
    [image_path,save_dir]=args

    max_num_iter=5
    n_segments=6000
    compactness=30   # 平衡颜色接近度和空间接近度。值越大，空间邻近性的权重越大，使超级像素形状更为方形/立方。

    start = time.time()
    img_bgr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    # img_rgb = io.imread(image_path)

    img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)

    '''均衡化'''
    img_hist = image_equalizeHist(cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR),'HSV')
    img_blur = image_blur(img_hist, 'medianBlur')

    mask = skimage.segmentation.slic(
        cv2.cvtColor(img_blur, cv2.COLOR_BGR2RGB), 
        n_segments=n_segments, 
        compactness=compactness,  
        max_num_iter=max_num_iter,
        sigma = 5,
        # spacing=[0.5,0.5], 
        # channel_axis=True, 
        convert2lab=True,
        enforce_connectivity=True, 
        # min_size_factor=0.5, 
        # max_size_factor=3,
        # slic_zero=False
        # start_label=1,
    )
 
    line = skimage.segmentation.mark_boundaries(img_rgb,mask,(1,0,0),(1,0,0),mode='inner')
    # ims = skimage.measure.regionprops(mask,intensity_image=img_rgb,cache=True,)
    print(time.time()-start)
    
   
    
    # regions = regionprops(mask, intensity_image=cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY))

    for i in range(np.min(mask), np.max(mask)+1):
        locat = np.where(mask==i)
        array0 = copy.deepcopy(img_bgr[
            int(min(locat[0])):int(max(locat[0])),
            int(min(locat[1])):int(max(locat[1])),
            :
        ])
        path = os.path.join(save_dir, f"{i}.png")
        cv2.imwrite(path,array0)


    plt.figure()
    plt.title(f'直方图均衡化',fontsize=20)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.subplot(111)
    plt.axis("off")
    # cmap = mpl.cm.get_cmap('prism')
    plt.imshow(img_rgb)
    time.sleep(1)

    plt.figure()
    plt.title(f'直方图均衡化',fontsize=20)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.subplot(111)
    plt.axis("off")
    plt.imshow(img_rgb)
    name =f"source_均衡化.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')
    
    time.sleep(1)

    plt.figure()
    plt.title(f'iters={max_num_iter},segments={n_segments},compactness={compactness}')
    plt.subplot(111)
    plt.axis("off")
    plt.imshow(line)
    name =f"{max_num_iter}-{n_segments}-{compactness}_slic_2.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    # for props in regions:
    #     cy, cx = props.centroid
    #     plt.plot(cx, cy, 'ro')
  
    plt.show()
    return


def image_felzenszwalb(image_path, save_dir):
   
    scale=500
    sigma=5
    min_size=100

    img_bgr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    '''直方图均衡化,去噪'''
    img_hist = image_equalizeHist(img_bgr,'HSV')
    img_blur = image_blur(img_hist, 'medianBlur')
    img_float = skimage.util.img_as_float(cv2.cvtColor(img_blur, cv2.COLOR_BGR2RGB))
    
    contour_masks = skimage.segmentation.felzenszwalb(
        img_float, 
        scale=scale, 
        sigma=sigma, 
        min_size=min_size,
        channel_axis=True 
    )

    img_line = skimage.segmentation.mark_boundaries(img_float,contour_masks,(1,0,0),(1,0,0),mode='inner')

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'sigma={sigma},scale={scale},min_size={min_size}')
    plt.subplot(111)
    plt.axis("off")
    plt.imshow(img_line,aspect='equal',origin="upper")
    name =f"felzenszwalb-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    time.sleep(1)

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'sigma={sigma},scale={scale},min_size={min_size}')
    plt.subplot(111)
    plt.axis("off")
    cmap = mpl.cm.get_cmap('prism')
    plt.imshow(contour_masks,cmap=cmap)
    name =f"felzenszwalb-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    plt.show()
    return


def quickshift_image(image_path,save_dir):
    kernel_size=5
    max_dist=1000
    ratio=0.2
    sigma=5
    random_seed=50

    img_bgr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    '''直方图均衡化,去噪'''
    img_hist = image_equalizeHist(img_bgr,'HSV')
    img_blur = image_blur(img_hist, 'medianBlur')

    img_float = skimage.util.img_as_float(cv2.cvtColor(img_blur, cv2.COLOR_BGR2RGB))
    contour_masks = skimage.segmentation.quickshift(
        img_float, 
        kernel_size=kernel_size, 
        max_dist=max_dist, 
        ratio=ratio,
        sigma=sigma,
        convert2lab=True,
        random_seed=random_seed,
    )
    img_line = skimage.segmentation.mark_boundaries(img_float,contour_masks,(1,0,0),(1,0,0),mode='inner')

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'max_dist={max_dist},kernel_size={kernel_size},ratio={ratio}')
    plt.subplot(111)
    plt.axis("off")
    plt.imshow(img_line,aspect='equal',origin="upper")
    name =f"quickshift-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    time.sleep(1)

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'max_dist={max_dist},kernel_size={kernel_size},ratio={ratio}')
    plt.subplot(111)
    plt.axis("off")
    cmap = mpl.cm.get_cmap('prism')
    plt.imshow(contour_masks,cmap=cmap)
    name =f"quickshift-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    plt.show()
    return


def image_watershed(image_path,save_dir):
  
    markers=250
    compactness=0.001

    img_bgr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    '''直方图均衡化,去噪'''
    img_hist = image_equalizeHist(img_bgr,'HSV')
    img_blur = image_blur(img_hist, 'medianBlur')
    img_rgb = cv2.cvtColor(img_blur, cv2.COLOR_BGR2RGB)
    img_gray = cv2.cvtColor(img_blur, cv2.COLOR_BGR2GRAY)
    gradient = skimage.filters.sobel(img_gray)
    contour_masks = skimage.segmentation.watershed(gradient, markers=markers, compactness=compactness)
    img_line = skimage.segmentation.mark_boundaries(
        img_rgb,
        contour_masks,
        color=(1,0,0),
        outline_color=(1, 0, 0),
        mode='outer'
    )
    img_line = skimage.segmentation.mark_boundaries(img_rgb,contour_masks,(1,0,0),(1,0,0),mode='inner')
    
    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'markers={markers},compactness={compactness}')
    plt.subplot(111)
    plt.axis("off")
    plt.imshow(img_line,aspect='equal',origin="upper")
    name =f"watershed-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    time.sleep(1)

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'markers={markers},compactness={compactness}')
    plt.subplot(111)
    plt.axis("off")
    cmap = mpl.cm.get_cmap('prism')
    plt.imshow(contour_masks,cmap=cmap)
    name =f"watershed-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    plt.show()

    return


def seeds_superpixels(args):
    [image_path,save_dir]=args
    
    num_iterations = 10
    num_superpixels= 100
    num_levels = 9
    prior = 5  # 值越小，边界越精细，值越大，边界越平滑，值在0-5
    num_histogram_bins = 10

    img_bgr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    '''直方图均衡化,去噪,转颜色空间'''
    img_hist = image_equalizeHist(img_bgr,'HSV')
    img_blur = image_blur(img_hist, 'medianBlur')

    img_color = cv2.cvtColor(img_blur, cv2.COLOR_BGR2Lab)
    height,width,channels = img_color.shape
    # results = []
    # for num_iterations in [x for x in range(10,11,1)]:
    start = time.time()
    '''初始化，并开始迭代，获得掩膜'''
    seeds = cv2.ximgproc.createSuperpixelSEEDS(
        width,height,channels,num_superpixels,num_levels,prior,num_histogram_bins,True
    )
    seeds.iterate(img_bgr,num_iterations) 
    contour_masks = seeds.getLabelContourMask()
    labels = seeds.getLabels()
    img_line = skimage.segmentation.mark_boundaries(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB),contour_masks,(1,0,0),(1,0,0),mode='inner')
    # results.append([num_iterations,img_line])
    print(time.time()-start)
    
    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'iters={num_iterations},histograms={num_histogram_bins},prior={prior},levels={num_levels},superpixels={num_superpixels}')
    plt.subplot(111)
    plt.axis("off")
    plt.imshow(img_line,aspect='equal',origin="upper")
    name =f"seeds-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'iters={num_iterations},histograms={num_histogram_bins},prior={prior},levels={num_levels},superpixels={num_superpixels}')
    plt.subplot(111)
    plt.axis("off")
    cmap = mpl.cm.get_cmap('prism')
    plt.imshow(labels,cmap=cmap)
    name =f"seeds-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    # for [param,result] in results:
    #     plt.figure()
    #     plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    #     plt.rcParams['axes.unicode_minus'] = False
    #     plt.title(f'num_iterations={param}')
    #     plt.subplot(111)
    #     plt.axis("off")
    #     plt.imshow(result,aspect='equal',origin="upper")
    plt.show()
    return


def grabcut_superpixels(image_path,save_dir):

    iterCount = 10

    img_bgr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    (height,wedth,channels) = img_bgr.shape
    mask = np.zeros((height,wedth), np.uint8)
    SIZE = (1, 65)
    bgdModel = np.zeros(SIZE, np.float64)
    fgdModel = np.zeros(SIZE, np.float64)
    # rect = (1, 1, wedth, height)
    rect = (1300, 1600, 1330, 1630)
    cv2.grabCut(img_bgr, mask, rect, bgdModel, fgdModel, iterCount, cv2.GC_INIT_WITH_RECT)

    mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
    img_result = img_bgr * mask2[:, :, np.newaxis]

    # 显示图片
    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title("grabcut")
    plt.axis("off")
    plt.subplot(111)
    cmap = mpl.cm.get_cmap('prism')
    plt.imshow(mask2,cmap=cmap)
    name =f"grabcut-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')
    time.sleep(1)

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title("grabcut")
    plt.axis("off")
    plt.subplot(111)
    plt.imshow(cv2.cvtColor(img_result, cv2.COLOR_BGR2RGB))
    name =f"grabcut-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')
    time.sleep(1)

    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title("original")
    plt.axis("off")
    plt.imshow(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB))
    name =f"grabcut-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    plt.show()
    return


def slicx_superpixels(args):
    [image_path,save_dir]=args

    num_iterations = 50  # 迭代次数
    region_size=200  # 超像素平均尺寸20（默认为10）
    ruler=50.0  # 超像素平滑度，默认10
    algorithm=101  # SLIC(100)、SLICO（默认:101）和MSLIC(102)三种可选

    # img_bgr = cv2.imread(image_path)
    img_bgr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    '''直方图均衡化,去噪,转颜色空间'''
    img_hist = image_equalizeHist(img_bgr,'HSV')
    img_blur = image_blur(img_hist,'medianBlur')
    img_color = cv2.cvtColor(img_blur, cv2.COLOR_BGR2Lab)

    # results = []
    # for num_iterations in [x for x in range(10,11,1)]:
    start = time.time()
    '''初始化，并开始迭代'''
    slic = cv2.ximgproc.createSuperpixelSLIC(img_color,algorithm,region_size,ruler) 
    slic.iterate(num_iterations)   
    mask_slic = slic.getLabelContourMask() #获取Mask，超像素边缘Mask==1
    labels = slic.getLabels()
    img_line = skimage.segmentation.mark_boundaries(cv2.cvtColor(img_blur, cv2.COLOR_BGR2RGB),mask_slic,(1,0,0),(1,0,0),mode='inner')
    # results.append([num_iterations,img_line])
    print(time.time()-start)

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'iters={num_iterations},region_size={region_size},ruler={ruler}')
    plt.subplot(111)
    plt.axis("off")
    plt.imshow(img_line,aspect='equal',origin="upper")
    name =f"slic-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    time.sleep(1)

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'iters={num_iterations},region_size={region_size},ruler={ruler}')
    plt.subplot(111)
    plt.axis("off")
    cmap = mpl.cm.get_cmap('prism')
    plt.imshow(labels,cmap=cmap)
    name =f"slic-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    # for [param,result] in results:
    #     plt.figure()
    #     plt.title(f'num_iterations={param}')
    #     plt.subplot(111)
    #     plt.axis("off")
    #     plt.imshow(result,aspect='equal',origin="upper")
    plt.show()

    # label_slic = slic.getLabels()                #获取超像素标签
    # number_slic = slic.getNumberOfSuperpixels()  #获取超像素数目

    # mask_inv_slic = cv2.bitwise_not(mask_slic)  
    # img_slic = cv2.bitwise_and(img,img,mask=mask_inv_slic) #在原图上绘制超像素边界
    return


def lsc_superpixels(image_path,save_dir):

    num_iterations = 50
    region_size= 300
    ratio= 0.091  # 默认值0.075

    # img_bgr = cv2.imread(image_path)  # 无法识别中文路径
    img_bgr = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
    '''直方图均衡化,去噪,颜色空间转换'''
    img_hist = image_equalizeHist(img_bgr,'HSV')
    img_blur = image_blur(img_hist, 'medianBlur')
    img_color = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2Lab)  

    # results = []
    # for num_iterations in [x for x in range(10,11,11)]:
    start = time.time()
    '''初始化，并开始迭代,获得掩膜'''
    lsc = cv2.ximgproc.createSuperpixelLSC(img_color,region_size,ratio)
    lsc.iterate(num_iterations)
    mask_lsc = lsc.getLabelContourMask()
    labels = lsc.getLabels()
    img_line = skimage.segmentation.mark_boundaries(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB),mask_lsc,(1,0,0),(1,0,0),mode='inner')
    # results.append([num_iterations,img_line])
    print(time.time()-start)

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'iters={num_iterations},region_size={region_size},ratio={ratio}')
    plt.subplot(111)
    plt.axis("off")
    plt.imshow(img_line,aspect='equal',origin="upper")
    name =f"lsc-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    time.sleep(1)

    plt.figure()
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'iters={num_iterations},region_size={region_size},ratio={ratio}')
    plt.subplot(111)
    plt.axis("off")
    cmap = mpl.cm.get_cmap('prism')
    plt.imshow(labels,cmap=cmap)
    name =f"lsc-{round(time.time(),0)}.png"
    plt.savefig(os.path.join(save_dir,name),bbox_inches='tight')

    # print(time.time()-start)
    # for [param,result] in results:
    #     plt.figure()
    #     plt.title(f'num_iterations={param}')
    #     plt.subplot(111)
    #     plt.axis("off")
    #     plt.imshow(result,aspect='equal',origin="upper")
    plt.show()
    return


def image_slic_superpixels(args):
    [image_path]=args

    image_rgb = skimage.io.imread(image_path)

    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'source')
    plt.axis("off")
    plt.imshow(image_rgb)

    image_float = skimage.util.img_as_float(image_rgb)

    # filter_image = filters.gaussian(image_float,sigma=2,mode='nearest',channel_axis=True)

    felzenszwalb = skimage.segmentation.felzenszwalb(image_float, scale=100, sigma=0.5, min_size=50)
    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'felzenszwalb')
    plt.axis("off")
    plt.imshow(skimage.segmentation.mark_boundaries(image_float, felzenszwalb))

    slic = skimage.segmentation.slic(image_float, n_segments=100, compactness=10, sigma=1)
    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'slic')
    plt.axis("off")
    plt.imshow(skimage.segmentation.mark_boundaries(image_float, slic))

    image_gray = skimage.color.rgb2gray(image_float)

    edges  = skimage.filters.sobel(image_gray)
    watershed = skimage.segmentation.watershed(edges, markers=100, compactness=0.001)
    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'watershed-sobel')
    plt.axis("off")
    plt.imshow(skimage.segmentation.mark_boundaries(image_float, watershed))

    edges  = skimage.filters.prewitt(image_gray)
    watershed = skimage.segmentation.watershed(edges, markers=100, compactness=0.001)
    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'watershed-prewitt')
    plt.axis("off")
    plt.imshow(skimage.segmentation.mark_boundaries(image_float, watershed))

    edges  = skimage.feature.canny(image_gray,sigma=1.0)
    watershed = skimage.segmentation.watershed(edges, markers=100, compactness=0.001)
    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'watershed-canny')
    plt.axis("off")
    plt.imshow(skimage.segmentation.mark_boundaries(image_float, watershed))

    edges  = skimage.filters.roberts(image_gray)
    watershed = skimage.segmentation.watershed(edges, markers=100, compactness=0.001)
    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'watershed-roberts')
    plt.axis("off")
    plt.imshow(skimage.segmentation.mark_boundaries(image_float, watershed))

    edges  = skimage.filters.scharr(image_gray)
    watershed = skimage.segmentation.watershed(edges, markers=100, compactness=0.001)
    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'watershed-scharr')
    plt.axis("off")
    plt.imshow(skimage.segmentation.mark_boundaries(image_float, watershed))

    quick = skimage.segmentation.quickshift(image_float, kernel_size=3, max_dist=10, ratio=0.5)
    plt.figure()
    plt.subplot(111)
    plt.rcParams['font.sans-serif']=['SimHei']#汉字防止出现乱码
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(f'quick')
    plt.axis("off")
    plt.imshow(skimage.segmentation.mark_boundaries(image_float, quick))
  
    plt.show()
    return


if __name__ == "__main__":
    '''grabcut_superpixels'''
    # image_path = r"E:\Image2\cweqm5huoa4vae9xxypn53l0_0.jpg"
    # image_path = r"E:\\新建文件夹\\keaidexiaomao_6599077.jpg"
    # image_path = r"E:\Image2\G50F008021_2_0_1_0.tif"
    # save_dir = r"E:\Yang\image"
    # image_path = r"E:\新建文件夹\\G50F008021_2_0_1_0_1.jpg"
    # grabcut_superpixels(image_path,save_dir)
    '''help'''
    # print(help(cv2.segmentation))
    # print(help(cv2.ximgproc.createSuperpixelSLIC))
    # print(help(cv2.ximgproc.createSuperpixelSLIC))
    # print(help(cv2.GaussianBlur))
    # print(help(mark_boundaries))
    # print(help(cv2.ximgproc.createSuperpixelSEEDS))
    # print(help(cv2.grabCut))
    '''lsc'''
    # image_path = r"E:\Image2\G50F008021_2_0_1_0.tif"
    # image_path = r"E:\\新建文件夹\\keaidexiaomao_6599077.jpg"
    # image_path = r"E:\\新建文件夹\\c3c33c0c00aa1e0283219b54952116a3.jpeg"
    # save_dir = r"E:\Yang\image"
    # lsc_superpixels(image_path,save_dir)
    '''quickshift_image'''
    # print(help(quickshift))
    # image_path = r"E:\Image2\G50F008021_2_0_1_0.tif"
    # save_dir = r"E:\Yang\image" 
    # quickshift_image(image_path,save_dir)
    ''''''
    '''felzenszwalb'''
    # print(help(felzenszwalb))
    # image_path = r"E:\Image2\G50F008021_2_0_1_0.tif"
    # save_dir = r"E:\Yang\image" 
    # image_felzenszwalb(image_path, save_dir)
    '''watershed'''
    # image_path = r"E:\Image2\G50F008021_2_0_1_0.tif"
    # save_dir = r"E:\Yang\image" 
    # image_watershed(image_path,save_dir)
    '''seeds'''
    # image_path = r"E:\Image2\G50F008021_2_0_1_0.tif"
    # save_dir = r"E:\Yang\image"
    # seeds_superpixels([image_path,save_dir])
    '''slicx'''
    # image_path = r"E:\Image2\G50F008021_2_0_1_0.tif"
    # save_dir = r"E:\Yang\image"
    # slicx_superpixels([image_path,save_dir])
    '''slic'''
    # image_path = r"E:\Image2\G50F008021_2_0_1_0.tif"
    # image_path = r"E:\Image2\cweqm5huoa4vae9xxypn53l0_0.jpg"
    # image_path = r"E:\\新建文件夹\\keaidexiaomao_6599077.jpg"
    # save_dir = r"E:\Yang\image"
    # image_slic([image_path,save_dir])
    '''slic_superpixels'''
    image_path = r"E:\Image2\G49F032048_22_12.tif"
    image_slic_superpixels([image_path])
    # print(dir(skimage.segmentation))
    # print(help(skimage.segmentation.slic_superpixels))
 